package com.maple.myskin.core.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;

import com.maple.myskin.R;

/**
 * Created by maple on 2020-07-29 17:37
 * E-Mail Address：740917401@qq.com
 */
public class SkinThemeUtils {
    private static int[] APPCOMPAT_COLOR_PRIMARY_DARK_ATTRS = {
            androidx.appcompat.R.attr.colorPrimaryDark
    };
    private static int[] STATUS_BAR_COLOR_ATTRS = {android.R.attr.statusBarColor, android.R.attr
            .navigationBarColor};

    private static int[] TYPEFACE_ATTRS = {R.attr.skinTypeface};

    /**
     * 通过属性值数组获取资源id数组
     *
     * @param context 上下文
     * @param attrs   属性值数组
     * @return 资源id数组
     */
    public static int[] getResId(Context context, int[] attrs) {
        int[] resIds = new int[attrs.length];
        TypedArray a = context.obtainStyledAttributes(attrs);
        for (int i = 0; i < attrs.length; i++) {
            resIds[i] = a.getResourceId(i, 0);
        }
        a.recycle();
        return resIds;
    }


    /**
     * 获取皮肤包的字体
     *
     * @param activity
     * @return 皮肤包的字体
     */
    public static Typeface getSkinTypeface(Activity activity) {
        //获取字体id
        int appTypefaceId = getResId(activity, TYPEFACE_ATTRS)[0];
        //去皮肤包中查找，并返回
        return SkinResources.getInstance().getTypeface(appTypefaceId);
    }


    /**
     * 更新状态栏和导航栏的颜色
     *
     * @param activity
     */
    public static void updateStatusNavigationBarColor(Activity activity) {
        //5.0以上才能修改
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return;
        }

        //获取 statusBarColor 与 navigationBarColor 当与colorPrimaryDark 不同时 以statusBarColor为准
        int[] statusBarColorResId = getResId(activity, STATUS_BAR_COLOR_ATTRS);
        //如果直接在style中写入固定颜色值(而不是 @color/XXX) 获得的是 0
        if (statusBarColorResId[0] != 0) {//状态栏
            activity.getWindow().setStatusBarColor(SkinResources.getInstance().getColor(statusBarColorResId[0]));
        } else {
            //获得 colorPrimaryDark
            int colorPrimaryDarkResId = getResId(activity, APPCOMPAT_COLOR_PRIMARY_DARK_ATTRS)[0];
            if (colorPrimaryDarkResId != 0) {
                activity.getWindow().setStatusBarColor(SkinResources.getInstance().getColor(colorPrimaryDarkResId));
            }
        }
        if (statusBarColorResId[1] != 0) {//导航栏
            activity.getWindow().setNavigationBarColor(SkinResources.getInstance().getColor(statusBarColorResId[1]));
        }
    }
}
